package parser

import (
	"fmt"
	"github.com/fatih/color"
	"github.com/hashicorp/hcl/v2"
	"github.com/ihaiker/tfwrapper/internal/config"
	"github.com/ihaiker/tfwrapper/internal/errors"
	"github.com/ihaiker/tfwrapper/internal/eval"
	"github.com/sirupsen/logrus"
	"github.com/zclconf/go-cty/cty"
)

const MaxIterations = 100

func evaluateGlobalsBlock(opts config.Running, file *hcl.File) (map[string]cty.Value, hcl.Diagnostics) {
	log := logrus.WithField("file", opts.RelPath())

	content, _, diags := file.Body.PartialContent(&hcl.BodySchema{
		Blocks: []hcl.BlockHeaderSchema{
			{Type: "globals"},
		},
	})
	if diags.HasErrors() || len(content.Blocks) == 0 {
		return nil, diags
	}

	if len(content.Blocks) > 1 {
		for _, block := range content.Blocks {
			diags = diags.Append(&hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "globals block must be unique",
				Detail:   fmt.Sprintf("globals block must be unique, but found %d.", len(content.Blocks)),
				Subject:  &block.DefRange,
			})
		}
		return nil, diags
	}

	wec, diags := eval.CreateEvalContext(opts)
	if diags.HasErrors() {
		return nil, diags
	}

	globals := make(map[string]cty.Value, 0)
	for i := MaxIterations; i >= 0; i-- {
		globals, diags = wec.DecodeBlockAttributes(content.Blocks[0])
		if !diags.HasErrors() {
			break
		}
		if diags.HasErrors() && errors.NotOnlyUnsupportedAttribute(diags) {
			return globals, diags
		}
		wec.AppendGlobals(globals)
	}

	for key, _ := range globals {
		log.Debugf("found globals variable: %s", color.HiMagentaString(key))
	}
	return globals, diags
}
